var ordernum = 0 //0代表全部，1代表待付款，2代表确认，3代表预定成功
var type = GetQueryString('type') //0代表全部订单，1代表房车租赁，2代表房车旅行
var page = 1 //页数
$(document).ready(function () {
  alterPhone()
  newInfo();
  modification() //x修改密码
  personage()
  common(); //请求常用信息列表
  WantOrder(0, type, 1)


   leftClick()
  ChooseType()
  ShowInfo() //模块切换 
  
  if( type == 'myCenter' ){
    $('.mol_left_item_item').eq(3).click()
  }

})


/**
 * 正则获取url参数
 */
function GetQueryString(name) {

   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");

   var r = window.location.search.substr(1).match(reg);

   if (r!=null) return (r[2]); return null;

}


//请求列表参数
var WantOrder = function (ordernum, type, page) {
  var imgb = basePath + '/static/pcsofangche/my/myorderlist/'
  $('div.mol_right_three').html('')
  $('div.mol_right_four_item').html('')
  // $("div.mol_right_personal").html("");
  console.log('ordernum=' + ordernum)
  console.log('type=' + type)
  console.log('page=' + page)
  if ( type == 0 ){
    $('.mol_right_one').html('全部订单')
    $('div.mol_left_item_item:eq('+ type +')').addClass('yellowt')
  }
  if ( type == 1 ){
    $('.mol_right_one').html('房车租赁')
    $('div.mol_left_item_item:eq('+ type +')').addClass('yellowt')
  }
  if ( type == 2 ){
    $('.mol_right_one').html('房车旅行')
    $('div.mol_left_item_item:eq('+ type +')').addClass('yellowt')
  }
  $('.mol_left_item').addClass('addClass')

  LoadingIcon = layer.load(0, { time: 10 * 1000 })
  $.ajax({
    dataType: 'json',
    type: 'post',
    url: basePath + '/my/sliorder',
    data: {
      ordernum: ordernum,
      type: type,
      page: page
    },
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    success: function (data) {
      // console.log("订单数据")
      // console.log(data)
      var code = data.code
      if (code == 1) {
        var h = ''

        for (var i = 0; i < data.data.length; i++) {
          if (data.data[i].type == 1) {
            var ordertype = data.data[i].type
            var state = data.data[i].state
            if (state == 1) {
              state = '待付款'
            } else if (state == 2) {
              state = '待确认'
            } else if (state == 3) {
              state = '预订成功'
            } else if (state == 4) {
              state = '出行中'
            } else if (state == 5) {
              state = '已完成'
            } else if (state == 6) {
              state = '确认完成'
            } else if (state == 7) {
              state = '申请退款中'
            } else if (state == 8) {
              state = '退款成功'
            }
            h =
              h +
              '<div class="mol_right_three_item">\n' +
              '<div class="row">\n' +
              '<div class="mol_right_three_item_pic col-lg-3 col-md-3">\n' +
              '<div class="mol_right_three_item_pic_top clearfix">\n' +
              '<div class="mol_right_three_item_pic_top_one">订单号：' +
              data.data[i].num +
              '</div>\n' +
              '<div class="mol_right_three_item_pic_top_two">【' +
              state +
              '】</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_pic_main">\n' +
              '<img src="' +
              data.data[i].picture +
              '" class="mol_right_three_item_pic_main_posi img-responsive" />\n' +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial col-lg-4 col-md-4">\n' +
              '<div class="mol_right_three_item_detial_title">' +
              data.data[i].productname +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_pick clearfix">\n' +
              '<div class="mol_right_three_item_detial_pick_icon">\n' +
              '<img src="' +
              imgb +
              'img/quche.png" class="mol_right_three_item_detial_pick_icon_posi" />\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_pick_time">' +
              data.data[i].begindate +
              data.data[i].begintime +
              data.data[i].city +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_pick clearfix">\n' +
              '<div class="mol_right_three_item_detial_pick_icon">\n' +
              '<img src="' +
              imgb +
              'img/huanche.png" class="mol_right_three_item_detial_pick_icon_posi" />\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_pick_time">' +
              data.data[i].enddate +
              data.data[i].endtime +
              data.data[i].city +
              '</div>\n' +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_price col-lg-5 col-md-5">\n' +
              '<div class="mol_right_three_item_price_top">下单时间：' +
              data.data[i].createtime +
              '</div>\n' +
              '<div class="mol_right_three_item_price_main">\n' +
              '<div class="mol_right_three_item_price_main_detail clearfix">\n' +
              '<div class="mol_right_three_item_price_main_detail_sigbol">总&nbsp;&nbsp;&nbsp;&nbsp;价：￥</div>\n' +
              '<div class="mol_right_three_item_price_main_detail_main">' +
              data.data[i].price +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_price_main_more">查看详情</div>\n' +
              '<text class="mol_right_three_item_price_main_more hidden">' +
              data.data[i].id +
              '</text>\n' +
              '</div>\n' +
              '</div>\n' +
              '</div>\n' +
              '</div>'
          } else if (data.data[i].type == 2) {
            var ordertype = data.data[i].type
            var state = data.data[i].state
            if (state == 1) {
              state = '待付款'
            } else if (state == 2) {
              state = '待确认'
            } else if (state == 3) {
              state = '预订成功'
            } else if (state == 4) {
              state = '出行中'
            } else if (state == 5) {
              state = '已完成'
            } else if (state == 6) {
              state = '确认完成'
            } else if (state == 7) {
              state = '申请退款中'
            } else if (state == 8) {
              state = '退款成功'
            }
            h =
              h +
              '<div class="mol_right_three_item">\n' +
              '<div class="row">\n' +
              '<div class="mol_right_three_item_pic col-lg-3 col-md-3">\n' +
              '<div class="mol_right_three_item_pic_top">\n' +
              '<div class="mol_right_three_item_pic_top_one">订单号：' +
              data.data[i].num +
              '</div>\n' +
              '<div class="mol_right_three_item_pic_top_two">【' +
              state +
              '】</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_pic_main">\n' +
              '<img src="' +
              data.data[i].picture +
              '" class="mol_right_three_item_pic_main_posi img-responsive" />\n' +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial col-lg-4 col-md-4">\n' +
              '<div class="mol_right_three_item_detial_title">' +
              data.data[i].productname +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_item clearfix">\n' +
              '<div class="mol_right_three_item_detial_item_icon"><img src="' +
              imgb +
              'img/address.png" class="mol_right_three_item_detial_item_icon_posi" /></div>\n' +
              '<div class="mol_right_three_item_detial_item_main">出发地：' +
              data.data[i].city +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_item clearfix">\n' +
              '<div class="mol_right_three_item_detial_item_icon"><img src="' +
              imgb +
              'img/rili.png" class="mol_right_three_item_detial_item_icon_posi" /></div>\n' +
              '<div class="mol_right_three_item_detial_item_main">出游日期：' +
              data.data[i].begindate +
              '出发</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_detial_item clearfix">\n' +
              '<div class="mol_right_three_item_detial_item_icon"></div>\n' +
              '<div class="mol_right_three_item_detial_item_main" style="text-indent:90px;">' +
              data.data[i].enddate +
              '返回</div>\n' +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_price col-lg-5 col-md-5">\n' +
              '<div class="mol_right_three_item_price_top">下单时间：' +
              data.data[i].createtime +
              '</div>\n' +
              '<div class="mol_right_three_item_price_main">\n' +
              '<div class="mol_right_three_item_price_main_detail clearfix">\n' +
              '<div class="mol_right_three_item_price_main_detail_sigbol">总&nbsp;&nbsp;&nbsp;&nbsp;价：￥</div>\n' +
              '<div class="mol_right_three_item_price_main_detail_main">' +
              data.data[i].price +
              '</div>\n' +
              '</div>\n' +
              '<div class="mol_right_three_item_price_main_more">查看详情</div>\n' +
              '<text class="mol_right_three_item_price_main_more hidden">' +
              data.data[i].id +
              '</text>\n' +
              '</div>\n' +
              '</div>\n' +
              '</div>\n' +
              '</div>'
          }
        }

        var p = ''
        for (var i = 0; i < data.pagesize; i++) {
          p = p + '<div class="mol_right_four_item_item">' + (i + 1) + '</div>'
        }
        $('div.mol_right_three').html(h)
        $('div.mol_right_four_item').html(p)
        // $("div.mol_right_personal").show();
        CheckMore()
        ChoosePage()
      }
    },
    error: function () {
      console.log('访问失败')
    },
    complete: function () {
      console.log('请求完成')
      layer.close(LoadingIcon)
    }
  })
}
//点击左侧事件
var leftClick = function () {
  // 会员主页
  $('div.mol_left_item:eq(0)').click(function () {
    // $("div.mol_right_personal").hide();
    $(this).addClass('yellowt')
    $('div.mol_left_item')
      .not(this)
      .removeClass('yellowt')
    $('div.mol_left_item_item').removeClass('yellowt')
    GivePicture()
  })
  // 全部订单
  $('div.mol_left_item_item:eq(0)').click(function () {
    window.location.href = (basePath+"/myorderlist?type=0");
  })
  // 房车租赁
  $('div.mol_left_item_item:eq(1)').click(function () {
    window.location.href = (basePath+"/myorderlist?type=1");
  })
  // 房车旅行
  $('div.mol_left_item_item:eq(2)').click(function () {
    window.location.href = (basePath+"/myorderlist?type=2");
  })
  // 个人信息
  $('div.mol_left_item_item:eq(3)').click(function () {
    $('.personal-form_cancel-btn').click()
    $('div.mol_left_item:eq(0)').removeClass('yellowt')
    $('div.mol_left_item:eq(1)').removeClass('yellowt')
    $('div.mol_left_item:eq(2)').addClass('yellowt')
    $(this).addClass('yellowt')
    $('div.mol_left_item_item')
      .not(this)
      .removeClass('yellowt')
    $('div.mol_right_personal').hide()
    $('div.mol_right_setting').hide()
    $('div.mol_right_info').show()
    $('div.mol_right_common').hide()
    $('div.mol_right_message').hide()
    $('div.mol_right').hide()
  })
  // 常用信息
  $('div.mol_left_item_item:eq(4)').click(function () {
    $('.news_cancel').click()
    $('div.mol_left_item:eq(0)').removeClass('yellowt')
    $('div.mol_left_item:eq(1)').removeClass('yellowt')
    $('div.mol_left_item:eq(2)').addClass('yellowt')
    $(this).addClass('yellowt')
    $('div.mol_left_item_item')
      .not(this)
      .removeClass('yellowt')
    $('div.mol_right_personal').hide()
    $('div.mol_right_setting').hide()
    $('div.mol_right_info').hide()
    $('div.mol_right_common').show()
    $('div.mol_right_message').hide()
    $('div.mol_right').hide()

    // console.log('常用信息')
  })
  // 账户设置
  $('div.mol_left_item_item:eq(5)').click(function () {
    $('div.mol_left_item:eq(0)').removeClass('yellowt')
    $('div.mol_left_item:eq(1)').removeClass('yellowt')
    $('div.mol_left_item:eq(2)').addClass('yellowt')
    $(this).addClass('yellowt')
    $('div.mol_left_item_item')
      .not(this)
      .removeClass('yellowt')
    $('div.mol_right_personal').hide()
    $('div.mol_right_setting').show()
    $('div.mol_right_info').hide()
    $('div.mol_right_common').hide()
    $('div.mol_right_message').hide()
    $('div.mol_right').hide()
    // console.log('账户设置')
  })
  // 绑定与关联
  $('div.mol_left_item_item:eq(6)').click(function () {
    var url = basePath+"/mycenter";
    url = encodeURI(url);
    url = encodeURI(url);
    window.location.href = (url);
  })
}

getAjax('/my/checkBindStatus',function(res){
  if(res.respCode == 1){
    $('div.mol_left_item_item:eq(6)').hide()
  }
})

function getAjax (url,fn){
  $.ajax({
    dataType : "json",
      url: basePath + url,
      type: 'GET',
      xhrFields: {
        withCredentials: true
      },
      contentType : "application/json",
      success: function(res) {
        if ( fn ){
          fn(res)
        }
      }
    })    
}

//点击会员主页和个人中心事件
var GivePicture = function () {
  var imgb = basePath + '/static/pcsofangche/my/myorderlist/'
  var img = '<img src="' + imgb + 'img/blinding.png" class="molshowpic" />'
  $('div.mol_right_three').html(img)
  $('div.mol_right_four_item').html('')
}

//点击选择ordernum事件
var ChooseType = function () {
  for (var i = 0; i < 4; i++) {
    $('div.mol_right_two_item:eq(' + i + ')').click(
      (function (i) {
        return function () {
          ordernum = i
          $(this).addClass('mol_right_two_itemchoose')
          $('div.mol_right_two_item')
            .not(this)
            .removeClass('mol_right_two_itemchoose')
          WantOrder(ordernum, type, 1)
        }
      })(i)
    )
  }
}
//点击查看详情事件
var CheckMore = function () {
  var len = $('text.mol_right_three_item_price_main_more').length
  for (var m = 0; m < len; m++) {
    $('div.mol_right_three_item_price_main_more:eq(' + m + ')').click(
      (function (m) {
        return function () {
          var orderid = $('text.mol_right_three_item_price_main_more:eq(' + m + ')').text()
          var url = basePath + '/orderlistlinerepay?orderid=' + orderid
          window.location.href = url
        }
      })(m)
    )
  }
}
//点击页数事件
var ChoosePage = function () {
  var len = $('div.mol_right_four_item_item').length
  for (var i = 0; i < len; i++) {
    $('div.mol_right_four_item_item:eq(' + i + ')').click(
      (function (i) {
        return function () {
          var p = $('div.mol_right_four_item_item:eq(' + i + ')').text()
          page = p
          WantOrder(ordernum, type, page)
        }
      })(i)
    )
  }
}
// 请求我的个人信息
var personage = function () {
  // console.log('请求个人信息')
  $.ajax({
    type: 'post',
    url: basePath + '/my/detail',
    data: {},
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    success: function (data) {
      var newData = JSON.parse(data)
      var result = template('one', newData.data)
      // console.log(newData)
      $('#personal_one').html(result)
      // ShowInfo();
      birthday();
      var birthdate = newData.data.birthdate.split('-')
      $(".year").find("option[value='"+ birthdate[0] +"']").attr("selected",true);
      $(".month").find("option[value='"+ birthdate[1] +"']").attr("selected",true);
      $(".day").find("option[value='"+ birthdate[2] +"']").attr("selected",true);
      // template.defaults.imports.spcli = function (value, d) {
      //   ShowInfo();
      //   birthday();
      // }
    }
  })
}
// 请求常用信息列表
var common = function () {
  // console.log('常用信息')
  $.ajax({
    type: 'post',
    url: basePath + '/my/contactList',
    data: {},
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    success: function (data) {
      var newData = JSON.parse(data)
      var result = template('two', newData);
      // console.log(newData)
      $('#linkman').html(result);
      // ShowInfo();
      pageInfo();
    }
  })
}
// 年月日下拉联动
var birthday = function () {
  var date = new Date()
  year = date.getFullYear() //获取当前年份
  var i = 1945
  var dropList
  for (i; i <= year; i++) {
    if (i == year) {
      dropList = dropList + "<option value='" + i + "' selected>" + i + '</option>'
    } else {
      dropList = dropList + "<option value='" + i + "'>" + i + '</option>'
    }
  }
  $('select[name=year]').html(dropList) //生成年份下拉菜单
  var monthly
  for (month = 1; month < 13; month++) {
    if ( month < 10 ){
      var newMonth = '0' + month
    }else{
      var newMonth =  month
    }
    monthly = monthly + "<option value='" + newMonth + "'>" + newMonth + '</option>'
  }
  $('select[name=month]').html(monthly) //生成月份下拉菜单
  var dayly
  for (day = 1; day <= 31; day++) {
    if ( day < 10 ){
      var newDay = '0' + day
    }else{
      var newDay =  day
    }
    dayly = dayly + "<option value='" + newDay + "'>" + newDay + '</option>'
  }
  $('select[name=day]').html(dayly) //生成天数下拉菜单
  /*
	 * 处理每个月有多少天---联动
	 */
  $('select[name=month]').change(function () {
    var currentDay
    var Flag = $('select[name=year]').val()
    var currentMonth = $('select[name=month]').val()
    switch (currentMonth) {
      case '1':
      case '3':
      case '5':
      case '7':
      case '8':
      case '10':
      case '12':
        var total = 31
        break
      case '4':
      case '6':
      case '9':
      case '11':
        var total = 30
        break
      case '2':
        if ((Flag % 4 == 0 && Flag % 100 != 0) || Flag % 400 == 0) {
          var total = 29
        } else {
          var total = 28
        }
      default:
        break
    }
    for (day = 1; day <= total; day++) {
      currentDay = currentDay + "<option value='" + day + "'>" + day + '</option>'
    }
    $('select[name=day]').html(currentDay) //生成日期下拉菜单
  })
}
// 个人中心模块切换
var ShowInfo = function () {
  // $('#identifier').modal(options);
  // 新增
  $(document).on('click','div.new_btn_info',function(){
    $('#common_info').hide()
    $('#new_common_info').show()
  })
  // $('div.new_btn_info').click(function () {
  //   $('#common_info').hide()
  //   $('#new_common_info').show()
  // })
  // 编辑
  // $('.common_edit_icon').click(function () {
  //   $('#common_info').hide()
  //   $('#xg_common_info').show()

  // })
  $(document).on('click','.common_ul .common_edit_icon',function() {
    // $('#common_info').hide()
    // $('#xg_common_info').show()
    var id = $(this).parents('.common_ul').data('id');
    compile(id)
    // console.log(id)
  })
  // 取消编辑
  $(document).on('click','.news_cancel',function () {
    $('#common_info').show()
    $('#new_common_info').hide()
    $('#xg_common_info').hide()
    common();
  })
  // 点击弹出模态框 
  $(document).on('click', '.common_remove_icon', function () {
    $('#myModal').modal('show');
    var id = $(this).parents('.common_ul').data('id');
    removeInfo(id)
    // console.log('模态框')
    // console.log(id);
  })
  // 个人信息
  $(document).on('click','.personal-form_edit-btn',function(){
    // e.preventDefault()
    // e.stopPropagation()
    $('.preview-active').hide()
    $('.edit-active').show()
    return false
  })
  // $('.personal-form_edit-btn').click(function (e) {
    
  //   return false
  // })
  // 取消
  $(document).on('click','.personal-form_cancel-btn',function(){
    // e.preventDefault()
    // e.stopPropagation()
    $('.preview-active').show()
    $('.edit-active').hide()
    personage();
    
    return false
  })
  // $(document).on('click','.personal-form_save-btn',function(){
  //   return false
  // })

  // 点击修改 切换修改手机页面
  // $('.personal-form_cancel-btn').unbind()
  $(document).on('click','.personal-form_modify-btn',function(e) {
    e.preventDefault()
    e.stopPropagation()
    alterPhone()
    $('.per_show').hide()
    $('.aletr_phone').show()
  });
  // 取消按钮
  $(document).on('click','.btn__cencel',function(e) {
    e.preventDefault()
    e.stopPropagation()
    $('.per_show').show()
    $('.aletr_phone').hide()
  })
  ConfigPer();
  birthday();
  upload();
}
// 上传头像图片
var upload = function () {
  $(document).on('change','#upload',function () {
    //   layer.msg(this.files[0]);
    var current_pic = this.files[0]
    preview_picture(current_pic)
    var formdata = new FormData();
    formdata.append('mineImg', this.files[0]);
    $.ajax({
      url: basePath + '/my/uploadMineImg',
      type: 'POST',
      data: formdata,
      cache: false,
      contentType: false,
      processData: false,
      success: function (res) {
        var data = JSON.parse(res)
        if ( data.respCode == 1){
          $('.pcHeadImg:hidden').val(data.data.ImgPath)  
        }
      }
    })
  })
  function preview_picture(pic) {
    var r = new FileReader()
    r.readAsDataURL(pic)
    r.onload = function (e) {
      $('#pic')
        .attr('src', this.result)
        .show()
    }
  }
}
// 提交个人信息
var ConfigPer = function () {
  $(document).on('click','.personal-form_save-btn',function (e) {
    var formdata = $('.personal-form').serialize()
    var data_params = decodeURIComponent(formdata,true); 
    var arr = data_params.split('&');
    var newArr = []
    var params = {}
    arr.forEach(function(e, index) {
      　　　　newArr = e.split('=')
      　　　　params[newArr[0]] = newArr[1]
      　　})
    var birthdate = params.year + '-' + params.month + '-' + params.day
    
    delete params.day
    delete params.month
    delete params.year
    params.birthdate = birthdate

    console.log(params)
    $.ajax({
      dataType : "json",
    	type: "POST",
    	url: basePath + "/my/updateUser",
    	data: JSON.stringify(params),
      contentType : "application/json",
    	async: false,
    	success: function (res) {
        layer.msg(res.msg)
        
       
        // $('.personal-form_cancel-btn').click()
        personage()

    		// console.log(data)
    		// $("#commonLayout_appcreshi").parent().html(data);
    		// console.log("提交成功");
    	},
    	error: function (request) {
    		console.log("提交失败");
    	},
    });
    return false
  })
}
// 修改密码 
var modification = function () {
  $(".sava_password").click(function (e) {
    e.preventDefault()
    e.stopPropagation()
    var flag = true;
    var pwd = $("#old_pwd").val();
    var newPwd = $('#set_pwd').val();
    var confirmPwd = $('#new_pwd').val();
    if (pwd == '' || newPwd == '' || confirmPwd == '') {
      flag = false;
      layer.msg('请输入完整再提交');
    }
    if (newPwd != confirmPwd) {
      flag = false;
      $("#new_msg").show();
    } else {
      $("#new_msg").hide();
    }
    if (flag) {
      var nes = { 
        pwd:pwd, 
        newPwd:newPwd, 
        confirmPwd:confirmPwd
      };
      // // console.log(nes)
      $.ajax({
        url: basePath + '/my/updatePwdByOld',
        type: "POST",
        dataType: 'JSON',
        data: JSON.stringify(nes),
        xhrFields: {
          withCredentials: true
        },
        beforeSend: function (req) {
          // req.setRequestHeader('Authorization', auth);
          req.setRequestHeader('Content-Type', 'application/json');  ///加这一行解决问题
        },
        success: function (data) {
          console.log(data);
          // data.JSON.stringify();
          layer.msg(data.msg);
        }
      })
    }
  })

}
// 新增常用信息
var newInfo = function () {
  $('#news_save').click(function () {
    var formdata = $('#newly_common').serialize();
    var data_params = decodeURIComponent(formdata,true); 
    var arr = data_params.split('&');
    var newArr = []
    var params = {}
    arr.forEach(function(e, index) {
      　　　　newArr = e.split('=')
      　　　　params[newArr[0]] = newArr[1]
      　　})
    var birthdate = params.year + '-' + params.month + '-' + params.day
    
    delete params.day
    delete params.month
    delete params.year
    params.birthdate = birthdate
    console.log(params)
    $.ajax({
      url: basePath + '/my/contactAdd',
      type: 'POST',
      data: JSON.stringify(params),
      xhrFields: {
        withCredentials: true
      },
      beforeSend: function(req) {
        // req.setRequestHeader('Authorization', auth);
        req.setRequestHeader('Content-Type', 'application/json') ///加这一行解决问题
      },
      success: function(data) {
        // layer.msg(data.meg);
        // console.log(data);
        var t_data = JSON.parse(data)
        if ( t_data.msg == '传递成功') {
          layer.msg('添加成功');
          $('#newly_common')[0].reset();  //清空表单
          $('.news_cancel').click()
          common()
        } else {
          layer.msg('添加失败')
        }
      }
    })
  })
}
// 删除联系人
var removeInfo = function (id) {
  $("#remove_btn").click(function () {
    var r_id = id;
    var data = { id: r_id }
    // console.log(data);
    // console.log(r_id)
    $.ajax({
      type: 'post',
      url: basePath + '/my/contactDel',
      data: JSON.stringify(data),
      xhrFields: {
        withCredentials: true
      },
      beforeSend: function (req) {
        // req.setRequestHeader('Authorization', auth);
        req.setRequestHeader('Content-Type', 'application/json');
      },
      success: function (data) {
        $('#myModal').modal('hide');
        $(".common_ul[data-id=" + r_id + "]").remove();
        common();
      }
    })
  })

}
// 常用信息分页
var pageInfo = function () {
  tabPage({
    pageMain: '.pageMain',
    pageNav: '#pageNav',
    pagePrev: '#prev',
    pageNext: '#next',
    curNum: 4, /*每页显示的条数*/
    activeClass: 'active', /*高亮显示的class*/
    ini: 0/*初始化显示的页面*/
  });
  function tabPage(tabPage) {
    var pageMain = $(tabPage.pageMain);
    /*获取内容列表*/
    var pageNav = $(tabPage.pageNav);
    /*获取分页*/
    var pagePrev = $(tabPage.pagePrev);
    /*上一页*/
    var pageNext = $(tabPage.pageNext);
    /*下一页*/


    var curNum = tabPage.curNum;
    /*每页显示数*/
    var len = Math.ceil(pageMain.find("li").length / curNum);
    /*计算总页数*/
    // console.log(len);
    var pageList = '';
    /*生成页码*/
    var iNum = 0;
    /*当前的索引值*/

    for (var i = 0; i < len; i++) {
      pageList += '<a href="javascript:;">' + (i + 1) + '</a>';
    }
    pageNav.html(pageList);
    /*头一页加高亮显示*/
    pageNav.find("a:first").addClass(tabPage.activeClass);

    /*******标签页的点击事件*******/
    pageNav.find("a").each(function () {
      $(this).click(function () {
        pageNav.find("a").removeClass(tabPage.activeClass);
        $(this).addClass(tabPage.activeClass);
        iNum = $(this).index();
        $(pageMain).find("li").hide();
        for (var i = ($(this).html() - 1) * curNum; i < ($(this).html()) * curNum; i++) {
          $(pageMain).find("li").eq(i).show()
        }

      });
    })


    $(pageMain).find("li").hide();
    /************首页的显示*********/
    for (var i = 0; i < curNum; i++) {
      $(pageMain).find("li").eq(i).show()
    }


    /*下一页*/
    pageNext.click(function () {
      $(pageMain).find("li").hide();
      if (iNum == len - 1) {
        layer.msg('已经是最后一页');
        for (var i = (len - 1) * curNum; i < len * curNum; i++) {
          $(pageMain).find("li").eq(i).show()
        }
        return false;
      } else {
        pageNav.find("a").removeClass(tabPage.activeClass);
        iNum++;
        pageNav.find("a").eq(iNum).addClass(tabPage.activeClass);
        //                    ini(iNum);
      }
      for (var i = iNum * curNum; i < (iNum + 1) * curNum; i++) {
        $(pageMain).find("li").eq(i).show()
      }
    });
    /*上一页*/
    pagePrev.click(function () {
      $(pageMain).find("li").hide();
      if (iNum == 0) {
        layer.msg('当前是第一页');
        for (var i = 0; i < curNum; i++) {
          $(pageMain).find("li").eq(i).show()
        }
        return false;
      } else {
        pageNav.find("a").removeClass(tabPage.activeClass);
        iNum--;
        pageNav.find("a").eq(iNum).addClass(tabPage.activeClass);
      }
      for (var i = iNum * curNum; i < (iNum + 1) * curNum; i++) {
        $(pageMain).find("li").eq(i).show()
      }
    })
    // return len;
  }
}
// 修改手机号码 步骤条
var alterPhone = function() {
  var step = 1; //步骤计数
  // 下一步
  // $('.step__item').each(function(index, item){
  //     if(step === index+1){
  //       $(this).removeClass('step__item_active')
  //       $(this).find('.step__item_step').attr('class', 'step__item_icon iconfont icon-wancheng').text('')
  //       $(this).next('.step__item').addClass('step__item_active')
  //     }
  // })


  // $(this).removeClass('step__item_active')
  // $(this).find('.step__item_step').attr('class', 'step__item_icon iconfont icon-wancheng').text('')
  // $(this).next('.step__item').addClass('step__item_active')
  $('.step__item').removeClass('step__item_active').eq(0).addClass('step__item_active')
  $('.step__item').find('i').attr('class','')
  $('.step__item').find('i').addClass('step__item_step')
  $('.step__item').find('i').eq(0).text(1)
  $('.step__item').find('i').eq(1).text(2)
  $('.new_phone').val('')
  $('.code').val('')
  $('.part').hide()
  $('.part').eq(step-1).show()



  $('.btn__next').unbind('click')
  $('.btn__next').bind('click',function(){
   

    if ( step == 1 ) {
      var phone = $('.new_phone').val()

      if ( !phone ){
        layer.msg('手机号不能为空');
        return false
      }

      var data = {
        phone:phone,
      }
      $.ajax({
        dataType : "json",
        type : "post",
        url : basePath+"/meb/phonecode?phone=" + phone,
        data : JSON.stringify(data),
        contentType : "application/json",
        success : function(res) {
          if ( res.code == 1 ){
            layer.msg(res.msg);

            $('.step__item').each(function(index, item){
              if(step === index+1){
                $(this).removeClass('step__item_active')
                $(this).find('.step__item_step').attr('class', 'step__item_icon iconfont icon-wancheng').text('')
                $(this).next('.step__item').addClass('step__item_active')
              }
            })

            step++;
            if(step > 1){
              $('.btn__prev').show();
              $('.btn__cencel').hide();
            }else{
              $('.btn__prev').hide();
            }
            // 全部完成
            if(step>3){
              $('.btn_elect').hide();
            }


            $('.part').hide()
            $('.part').eq(step-1).show()

          }
        }
      })
    }

    /**
     * 修改手机号
     */
    if ( step == 2 ) {
      var phone = $('.new_phone').val()
      var code = $('.code').val()
      var data = {
        phone:phone,
        code:code
      }

      if ( !code ){
        layer.msg('验证码不能为空');
        return false
      }

      $.ajax({
        dataType : "json",
        type : "post",
        url : basePath+"/my/codeVer",
        data : JSON.stringify(data),
        contentType : "application/json",
        success : function(res) {
          layer.msg(res.msg);
          if ( res.respCode == 1 ){
            personage()
            $('.per_show').show()
            $('.aletr_phone').hide()
          }
        }
      })
    }
    
  })

  // 上一步
  $('.btn__prev').unbind('click')
  $('.btn__prev').bind('click',function(){
    $('.step__item').each(function(index, item){
      if(step === index+1){
        $(this).removeClass('step__item_active')
        $(this).prev('.step__item').addClass('step__item_active')
        $(this).prev('.step__item').find('.step__item_icon').attr('class', 'step__item_step').text(step-1)
      }
    })
    step--;
    
    if(step > 1){
      $('.btn__cencel').hide();
      $('.btn__prev').show();
    }else{
      $('.btn__prev').hide();
      $('.btn__cencel').show();
    }

    $('.part').hide()
    $('.part').eq(step-1).show()
  })
}
// 编辑联系人  -修改常用信息
var compile  = function (id) {
  var r_id = id;
  var data = { id:r_id }
  // console.log(data);
  $.ajax({
    url: basePath + '/my/contactDetail',
    type: 'post',
    data:JSON.stringify(data),
    xhrFields: {
      withCredentials: true
    },
    beforeSend: function (req) {
      // req.setRequestHeader('Authorization', auth);
      req.setRequestHeader('Content-Type', 'application/json'); 
    },
    success: function (data) {
      // 转换数据 *******待办
      var newData = JSON.parse(data)
      var year = newData.data[0].birthdate.slice(0,4)
      var month = newData.data[0].birthdate.slice(5,7)
      var day = newData.data[0].birthdate.slice(8,10)
      delete newData.data[0].birthdate
      newData.data[0].year = year
      newData.data[0].month = month
      newData.data[0].day = day
      // console.log(newData)
      var result = template('three', newData);
      $('#common_info').hide()
      $('#xg_common_info').show()
      $('#common_i').html(result);

      console.log(year)
      console.log(month)
      console.log(day)
      


      // ShowInfo();
      birthday();
      SaveContacts();

      $(".birthYear").find("option[value='"+ year +"']").attr("selected",true);
      $(".birthMonth").find("option[value='"+ month +"']").attr("selected",true);
      $(".birthDay").find("option[value='"+ day +"']").attr("selected",true);
    }

  })
}
// 保存编辑
var SaveContacts = function() {
  $('#edit_save').click(function() {
    var formdata = $('#Modify_Contacts').serialize();
    var data_params = decodeURIComponent(formdata,true); 
    // console.log(data_params);
    var arr = data_params.split('&');
    var newArr = []
    var params = {}
    arr.forEach(function(e, index){
      　　　　newArr = e.split('=')
      　　　　params[newArr[0]] = newArr[1]
      　　})
    var birthdate = params.year + '-' + params.month + '-' + params.day
    
    delete params.day
    delete params.month
    delete params.year
    params.birthdate = birthdate
    // console.log(params)
    $.ajax({
      url: basePath + '/my/contactAdd',
      type: 'POST',
      data: JSON.stringify(params),
      xhrFields: {
        withCredentials: true
      },
      beforeSend: function(req) {
        // req.setRequestHeader('Authorization', auth);
        req.setRequestHeader('Content-Type', 'application/json') ///加这一行解决问题
      },
      success: function(data) {
        // layer.msg(data.meg);
        // console.log(data);
        var t_data = JSON.parse(data)
        if ( t_data.msg == '传递成功') {
          layer.msg('编辑用户信息成功！');
          $('#newly_common')[0].reset();  //清空表单
          $('.news_cancel').click()
          common()
        } else {
          layer.msg('编辑用户失败！')
        }
      }
    })
  }) 
}
